const Service = require('egg').Service;
const { error, success } = require('../utils/response.js')
const fs = require('fs');
const path = require('path')
const moment = require('moment')

class articleService extends Service {
    // 获取文章 分页加筛选
    async getPage(info, ctx) {
        const limit = info.limit || 10;
        const page = info.page || 1;
        let { title,type } = info;
        if (title === '') title = null;
        // 获取分页数据
        const res = await this.app.mysql.query(`select a.id as id,a.content as content,a.createTime as createTime,a.userId as userId,a.image as image,u.image as userImage,a.likes as likes,u.nickname as nickname,a.outline as outline,u.status as status,a.title as title,a.type as type,u.username as username from user u,article a where (u.id=a.userId) and (a.type=?) and (a.title like concat('%',?,'%') or ? is null) order by createTime desc limit ? offset ?`, [type,title, title, Number(limit), (page - 1) * limit]);
        // 获取总页数
        const resTotal = await this.app.mysql.query(`select count(id) from article where type=? and (title like concat('%',?,'%') or ? is null)`,[type,title,title]);
        const totalPage = Math.ceil(resTotal[0]['count(id)'] / limit);
        res.forEach(element => {
            delete element.password
            element.createTime = moment(Number(element.createTime)).format('YYYY-MM-DD HH:mm:ss');
        });
        success(ctx, '获取成功', { totalPage, currentPage: Number(page), total: resTotal[0]['count(id)'], data: res })
    }

    // 添加文章功能
    async add(info,file, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        const {type} = info;
        if(type === 'news' && userInfo.status === 0 ) return error(ctx, '没有权限添加新闻');
        // 存储图片
        let filedata = fs.readFileSync(file.filepath);
        // 获取文件扩展名
        const fext = path.extname(file.filepath);
        const now = moment().valueOf();
        const filePath = `/public/images/article/${now}${fext}`
        fs.writeFileSync(path.join(__dirname, `..${filePath}`), filedata);
        info.image = filePath;
        const res = await this.app.mysql.insert('article', { ...info, userid: userInfo.id, createTime: now})
        if (res.affectedRows !== 1) error(ctx, '添加文章！请检查后台服务')
        success(ctx, '添加成功！')
    }
    // 删除文章功能  需要管理员权限
    async delete(info, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        if (userInfo.status === 0) return error(ctx, '没有该接口的权限')
        const {id} = info
        // 删除文章
        const res = await this.app.mysql.delete('article',{id});
        if(res.affectedRows !== 1) error(ctx, '删除文章失败！请检查后台服务')
        // 删除相关评论
        const res1 = await this.app.mysql.query(`delete from articlecom where newsId = ?`,[id]);
        success(ctx, '删除成功')
    }
    // 获取文章评论
    async getComPage(info, ctx){
        const limit = info.limit || 10;
        const page = info.page || 1;
        const {newsId} = info;
        const res = await this.app.mysql.query(`select * from user u,articlecom a where a.newsId=? and u.id=a.userId order by createTime desc limit ? offset ?`, [newsId,Number(limit), (page - 1) * limit]);
        // 获取总页数
        const resTotal = await this.app.mysql.query(`select count(id) from articlecom where newsId=?`,[newsId]);
        const totalPage = Math.ceil(resTotal[0]['count(id)'] / limit);
        res.forEach(element => {
            delete element.password
            element.createTime = moment(Number(element.createTime)).format('YYYY-MM-DD HH:mm:ss');
        });
        success(ctx, '获取成功',{totalPage,currentPage:Number(page),total: resTotal[0]['count(id)'],data:res})
    }
    // 添加文章评论
    async addComPage(info, ctx){
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        const now = moment().valueOf();
        const res = await this.app.mysql.insert('articlecom',{...info,userId:userInfo.id,createTime:now})
        if (res.affectedRows !== 1) error(ctx, '添加评论失败！请检查后台服务')
        success(ctx, '添加成功！')
    }
    // 删除评论功能  需要登录权限
    async deleteCom(info, ctx) {
        const token = ctx.request.header.authorization;
        const userInfo = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
        if (userInfo.status === 0) return error(ctx, '没有该接口的权限')
        const {id} = info
        const res = await this.app.mysql.delete('articlecom',{id});
        if(res.affectedRows !== 1) error(ctx, '删除评论失败！请检查后台服务')
        success(ctx, '删除成功')
    }
}
module.exports = articleService;